<template>
  <div class="page-main" :class="screenClass">
    <page-title :has-line="true">三码验证</page-title>
    <div class="scan">
      <div class="scan-title">请扫码成品三码信息</div>
      <a-form
        ref="formRef"
        layout="vertical"
        :model="form"
        auto-label-width
        :rules="rules"
      >
        <a-row :gutter="48">
          <a-col :span="8">
            <a-form-item field="barcodeWbz" label="外包装条码">
              <a-input
                ref="barcodeWbzInput"
                v-model="form.barcodeWbz"
                placeholder="请扫码或输入"
                @keydown.enter="wbzEnterKeyDown"
              >
                <template #suffix>
                  <icon-scan />
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="barcodeLlb" label="履历本条码">
              <a-input
                ref="barcodeLlbInput"
                v-model="form.barcodeLlb"
                placeholder="请扫码或输入"
                @keydown.enter="llbEnterKeyDown"
              >
                <template #suffix>
                  <icon-scan />
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="barcodeSwbm" label="实物表面条码">
              <a-input
                ref="barcodeSwbmInput"
                v-model="form.barcodeSwbm"
                placeholder="请扫码或输入"
                @keydown.enter="swbmEnterKeyDown"
              >
                <template #suffix>
                  <icon-scan />
                </template>
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item field="deliverType" label="附加条码">
              <a-input
                ref="mdsVendorInput"
                v-model="form.notecode"
                placeholder="请扫码或输入"
                @keydown.enter="mdsEnterKeyDown"
              >
                <template #suffix>
                  <icon-scan />
                </template>
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="info">
        <div class="mes">{{ showNoteCodeMes }}</div>
      </div>
    </div>
    <table-container
      v-model:columns="columns"
      v-model:is-fullscreen="isFullscreen"
      :loading="detailTableLoading"
      :all-columns="allColumns"
      @refresh="getDetailTableList"
    >
      <template #container-side>
        <a-space>
          <a-button
            v-permission="['pms:dcd-sn-mian:threeCodeVerification']"
            class="no-margin"
            @click="handleSaveForm"
            >保存</a-button
          >
          <a-button
            v-permission="['pms:dcd-sn-mian:Revoke']"
            class="no-margin"
            :disabled="!detailSelectedKeys.length"
            @click="handleRevoke"
            >撤销</a-button
          >
          <a-button class="no-margin" @click="handleConfig">页面配置</a-button>
          <div class="nocontact r-color">
            <span class="icon r-bg-color"></span>
            不能关联
          </div>
          <div class="contact g-color">
            <span class="icon g-bg-color"></span>
            能关联
          </div>
        </a-space>
      </template>
      <standard-table
        ref="detailTable"
        v-model:selectedKeys="detailSelectedKeys"
        height="calc(100vh - 584px)"
        :component-config="tableComponentConfig"
        :render-config="tableRenderConfig"
        :render-keys="detailTableRenderKeys"
        :loading="detailTableLoading"
        :data="detailTableData"
        :total="detailTableTotal"
        :row-class="rowClassFun"
        row-selection-type="checkbox"
        @init-columns-end="initColumns"
        @selection-change="detailSelectionChange"
        @page-change="detailPageChange"
        @page-size-change="detailPageSizeChange"
      >
        <template #operate="{ record, rowIndex }">
          <a-button
            v-permission="['pms:receive-detail-batch:updateAll']"
            type="text"
            :hidden="!['0', '10'].includes(record.billStatus)"
            @click="handleEdit(record, rowIndex)"
            >编辑</a-button
          >
          <a-button
            v-permission="['pms:dcd-sn-mian:deleteReceivedetailBatch']"
            type="text"
            :hidden="!['0', '10'].includes(record.billStatus)"
            @click="handleDelete(record, rowIndex)"
            >删除</a-button
          >
        </template>
      </standard-table>
    </table-container>
    <EditModal
      v-if="editModelVisible"
      v-model="editModelVisible"
      :select-id="selectBatchId"
      @fetch-data="getDetailTableList"
    ></EditModal>
    <ConfigModal
      v-if="configModelVisible"
      v-model="configModelVisible"
      :base-data="conifgForm"
      @update-config="updateConfig"
    ></ConfigModal>
    <CancelModal
      v-if="cancelModelVisible"
      v-model="cancelModelVisible"
    ></CancelModal>
  </div>
</template>

<script lang="ts" setup>
  import {
    computed,
    defineAsyncComponent,
    onMounted,
    provide,
    reactive,
    ref,
  } from 'vue';
  import StandardTable from '@/common/components/standard-table/index.vue';
  import TableContainer from '@/common/components/table-container/index.vue';
  import {
    deletePmsBatch,
    getPmsDcdPageDetail,
    getPmsSerialConfig,
    revokePmsBatch,
    saveThreeCode,
  } from '@/api/purchaseArrival/threeCodeVerification';
  import { useRoute } from 'vue-router';
  import lodash from 'lodash';
  import { Message } from '@arco-design/web-vue';
  import pageTitle from '@/common/components/title/page-title.vue';
  import { info } from '@/common/utils/modal-promise';
  import useFullScreen from '@/common/hooks/fullScreen';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from '../moduleCommon/tableComp/baseTableConfig';
  import {
    transitionAddInfo,
    transitionBarcode,
    valiScanCodeAndSetInput,
    valiScanCodeAutoSubmit,
  } from './PmsReceiveLValidCode4Serial';

  // 异步加载组件
  const ConfigModal = defineAsyncComponent(() => import('./ConfigModal.vue'));
  const CancelModal = defineAsyncComponent(() => import('./CancelModal.vue'));
  const EditModal = defineAsyncComponent(
    () => import('../purchaseArrivalDetails/EditModal.vue')
  );
  const barcodeWbzInput = ref(null);
  const barcodeLlbInput = ref(null);
  const barcodeSwbmInput = ref(null);
  const mdsVendorInput = ref(null);
  const editModelVisible = ref(false);
  const configModelVisible = ref(false);
  const cancelModelVisible = ref(false);
  const form = reactive({
    barcodeWbz: null,
  });
  let conifgForm = reactive({
    barcodeWbz: null,
  });
  const { isFullscreen, screenClass } = useFullScreen();
  // detail-list
  const detailTable = ref(null);
  const detailSelectedKeys = ref([]);
  const detailTableRenderKeys = [
    'secretLevel',
    'barcode1',
    'filed1', // 能否关联物品码和单件信息
    'filed2', // 三码验证结果
    'mdsItemCode',
    'mdsItemName',
    'partQty',
    'reqQty',
    'recprtlotNo',
    'batchNo',
    'itemSerialNo',
    'suplyStatus',
    'invReceiveQty',
    'pmsReceiveQty',
    'lfackoryDate',
    'manuDate',
    'mdsInventoryName',
    'invDateNum',
    'archiveDate',
    'preservationTime1',
    'acceptanceDate',
    'lifetimeNum',
    'scanfFirstDate',
    'scanfUseDate',
    'scanfSureDate',
    'weight',
    'weightUnit',
    'threeStartDate',
    'storageDate',
    'oilSealDate',
    'recheckDate',
    'pmsReceiveDate',
    'arrivalDate',
    'checkTimeType',
    'mdsUnitRate',
    'operate',
  ];
  const route = useRoute();
  const detailTableLoading = ref(false);
  const saveLoading = ref(false);
  const detailTableData = ref([]);
  const selectDetailId = ref();
  const detailTableTotal = ref(0);
  const selectBatchId = ref(null);
  const showNoteCodeMes = ref('暂无数据');
  const columns = ref<object[]>([]);
  const allColumns = ref<object[]>([]);
  const initColumns = (data: any[]) => {
    columns.value = lodash.cloneDeep(data);
    allColumns.value = lodash.cloneDeep(data);
  };
  let detailSelectRowList: Array<any> = [];
  const detailSelectionChange = (rowKeys: (string | number)[]) => {
    if (rowKeys && rowKeys.length) {
      detailSelectRowList = rowKeys;
      const [selectId] = detailSelectRowList;
      selectDetailId.value = selectId;
    }
  };
  let selectBatchRow = reactive({});
  provide(
    'selectBatchRow',
    computed(() => {
      return selectBatchRow;
    })
  );
  const detailPageChange = () => {
    getDetailTableList();
  };
  const detailPageSizeChange = () => {
    getDetailTableList();
  };
  const getDetailTableList = async (query = {}) => {
    const page = detailTable.value.getStatus();
    detailSelectedKeys.value = [];
    detailTableLoading.value = true;
    const { data } = await getPmsDcdPageDetail({
      ...query,
      ...page,
      barcodeStatus: '5',
    });
    // set两个值
    data.list = data.list.map((row) => {
      let filed1 = '';
      let color = 'green';
      if (row.barScanProdResult === 'N') {
        filed1 += '机载单件码没有找到，';
        color = 'red';
      } else {
        filed1 += '机载单件码解析成功，';
      }
      if (row.barScanItemResult === 'N') {
        filed1 += '物品码没有找到';
        color = 'red';
      } else {
        filed1 += '物品码解析成功';
      }
      let filed2 = '';
      if (row.barScanProdResult === 'N') {
        filed2 = '无单件信息';
      }
      if (row.barScanItemResult === 'N') {
        filed2 = '无物品信息';
      }
      if (row.barScanProdResult !== 'N' && row.barScanItemResult !== 'N') {
        filed2 = '验证成功';
      }
      return {
        ...row,
        filed1,
        filed2,
        color,
      };
    });
    detailTableData.value = data.list;
    detailTableTotal.value = data.total;
    detailTableLoading.value = false;
  };
  const handleConfig = () => {
    configModelVisible.value = true;
  };
  const updateConfig = (val) => {
    conifgForm = Object.assign(conifgForm, val);
  };
  const rowClassFun = (val) => {
    return val.raw.color;
  };
  const handleEdit = (row) => {
    selectBatchRow = Object.assign(selectBatchRow, row);
    selectBatchId.value = row.id;
    editModelVisible.value = true;
  };
  const handleSaveForm = () => {
    if (!checkForm()) return;
    if (saveLoading.value) return;
    saveLoading.value = false;
    const resultList = [];
    let myNodeName = 'barcodeOutPack';
    let result = valiScanCodeAndSetInput(
      form.barcodeWbz,
      myNodeName,
      valiScanCallBack,
      getInputValue
    );
    resultList.push(result);
    myNodeName = 'barcodeResume';
    result = valiScanCodeAndSetInput(
      form.barcodeLlb,
      myNodeName,
      valiScanCallBack,
      getInputValue
    );
    resultList.push(result);
    myNodeName = 'barcodeEntity';
    result = valiScanCodeAndSetInput(
      form.barcodeSwbm,
      myNodeName,
      valiScanCallBack,
      getInputValue
    );
    resultList.push(result);
    myNodeName = 'barcodeNote';
    if (form.notecode) {
      result = valiScanCodeAndSetInput(
        form.notecode,
        myNodeName,
        valiScanCallBack,
        getInputValue
      );
      resultList.push(result);
    }
    if (resultList.every((item) => item !== '-1')) {
      valiScanAndSave(1, myNodeName);
    }
  };
  const saveForm = async () => {
    if (!checkForm()) return;
    let formDataVal = {};
    saveLoading.value = true;
    if (form.notecode) {
      const { display, noteObj } = transitionAddInfo(form.notecode);
      if (display) {
        showNoteCodeMes.value = display;
      } else {
        showNoteCodeMes.value = '解析失败，暂无数据';
      }
      formDataVal = noteObj;
    }
    const formData = {
      // barcode: 'Mc1t!#!W12345678!#!Sc1t',
      // barcode: `${form.barcodeWbz}!#!${form.barcodeLlb}!#!${form.barcodeSwbm}`,
      barcode: transitionBarcode(form.barcodeWbz),
      // scanfSureDate: '2024-05-10 09:18:43',
      // scanfUseDate: '100',
      // scanfFirstDate: '2024-05-11 09:16:43',
      // scanfCloseDate: '2024-05-12 09:16:43',
      // scanfGetDate: '2024-05-13 09:16:43',
      barcodeWbz: form.barcodeWbz,
      barcodeLlb: form.barcodeLlb,
      barcodeSwbm: form.barcodeSwbm,
      notecode: form.notecode,
      receiveDetailId: route.query.receiveDetailId || null,
      // scanfQty: '2',
      // scanfProduceDate: '2024-05-10 09:16:43',
      // scanfActualWeight: '25',
      ...formDataVal,
    };
    try {
      const data = await saveThreeCode(formData);
      console.log(data);
    } finally {
      getDetailTableList();
      saveLoading.value = false;
    }
  };
  function checkForm() {
    if (!form.barcodeWbz) {
      Message.info({
        content: '请输入或扫描外包装条码编码！',
        duration: 5 * 1000,
      });
      return false;
    }
    if (!form.barcodeLlb) {
      Message.info({
        content: '请输入或扫描履历本条码编码！',
        duration: 5 * 1000,
      });
      return false;
    }
    if (!form.barcodeSwbm) {
      Message.info({
        content: '请输入或扫描实物表面条码编码！',
        duration: 5 * 1000,
      });
      return false;
    }
    return true;
  }
  const handleRevoke = async () => {
    if (!detailSelectedKeys.value.length) {
      Message.info({
        content: '请选择三码信息！',
        duration: 5 * 1000,
      });
      return;
    }
    const formData = {
      receiveDetailBatchIdList: detailSelectedKeys?.value,
      receiveDetailId: null,
    };
    await revokePmsBatch(formData);
    Message.success({
      content: '撤销成功！',
      duration: 5 * 1000,
    });
    detailSelectedKeys.value = [];
    getDetailTableList();
  };
  const handleDelete = async (row) => {
    await info({
      title: '删除确认',
      content: '您确定要删除当前所选的数据？',
      okText: '确认',
    });
    const { id } = row;
    await deletePmsBatch([id]);
    Message.success({
      content: '删除成功！',
      duration: 5 * 1000,
    });
    getDetailTableList();
  };
  // 老系统字段与新页面的映射
  const keyMap = {
    barcodeOutPack: {
      formName: 'barcodeWbz',
      inputRef: barcodeWbzInput.value,
    },
    barcodeResume: {
      formName: 'barcodeLlb',
      inputRef: barcodeLlbInput.value,
    },
    barcodeEntity: {
      formName: 'barcodeSwbm',
      inputRef: barcodeSwbmInput.value,
    },
    barcodeNote: {
      formName: 'notecode',
      inputRef: mdsVendorInput.value,
    },
  };
  const valiScanCallBack = (funName, ...arg) => {
    if (funName === 'setInput') {
      const inputName = arg[0];
      const inputValue = arg[1];
      form[keyMap[inputName].formName] = inputValue;
    }
    if (funName === 'setScanCodeObjFocus') {
      let onetime = false;
      Object.keys(keyMap).forEach((key) => {
        if (onetime) return;
        if (!form[keyMap[key].formName]) {
          onetime = true;
          keyMap[key].inputRef.focus();
        }
      });
    }
    if (funName === 'setFocus') {
      const inputName = arg[0];
      keyMap[inputName].inputRef.focus();
    }
    if (funName === 'saveData') {
      saveForm();
    }
  };
  function getInputValue(inputName) {
    if (inputName === 'barcodeOutPack') {
      return form.barcodeWbz;
    }
    if (inputName === 'barcodeResume') {
      return form.barcodeLlb;
    }
    if (inputName === 'barcodeEntity') {
      return form.barcodeSwbm;
    }
    if (inputName === 'barcodeNote') {
      return form.notecode;
    }
    return '';
  }
  /**
   * 外包装条码、履历本条码、实物表面条码都有数据，去后台查询
   * 数据不全跳转到下一个条码框
   * 如果是附加信息，三码都全的情况下去后台更新数据，三码不全跳到没数据的条码
   */
  const valiScanAndSave = (result, myNodeName) => {
    if (result !== '-1') {
      if (form.notecode) {
        // 判断附加码是否可以解析成功
        const transitionAddInfoFlag = transitionAddInfo(form.notecode);
        if (!transitionAddInfoFlag) {
          return false;
        }
      }
      // 验证数据是否可以提交后台
      valiScanCodeAutoSubmit(myNodeName, valiScanCallBack, getInputValue);
    }
    return false;
  };

  const wbzEnterKeyDown = () => {
    const myNodeName = 'barcodeOutPack';
    const result = valiScanCodeAndSetInput(
      form.barcodeWbz,
      myNodeName,
      valiScanCallBack,
      getInputValue
    );
    valiScanAndSave(result, myNodeName);
  };
  const llbEnterKeyDown = () => {
    const myNodeName = 'barcodeResume';
    const result = valiScanCodeAndSetInput(
      form.barcodeLlb,
      myNodeName,
      valiScanCallBack,
      getInputValue
    );
    valiScanAndSave(result, myNodeName);
  };
  const swbmEnterKeyDown = () => {
    const myNodeName = 'barcodeEntity';
    const result = valiScanCodeAndSetInput(
      form.barcodeSwbm,
      myNodeName,
      valiScanCallBack,
      getInputValue
    );
    valiScanAndSave(result, myNodeName);
  };
  const mdsEnterKeyDown = () => {
    const myNodeName = 'barcodeNote';
    if (form.notecode) {
      valiScanCodeAndSetInput(
        form.notecode,
        myNodeName,
        valiScanCallBack,
        getInputValue
      );
    }
    valiScanAndSave(2, myNodeName);
  };
  onMounted(() => {
    init();
  });
  const init = async () => {
    barcodeWbzInput.value.focus();
    keyMap.barcodeOutPack.inputRef = barcodeWbzInput.value;
    keyMap.barcodeResume.inputRef = barcodeLlbInput.value;
    keyMap.barcodeEntity.inputRef = barcodeSwbmInput.value;
    keyMap.barcodeNote.inputRef = mdsVendorInput.value;
    try {
      const { data } = await getPmsSerialConfig();
      conifgForm = Object.assign(conifgForm, data);
    } catch (error) {
      console.log(error);
    }
    getDetailTableList();
  };
</script>

<style lang="less" scoped>
  @import url('../moduleCommon/common.less');

  .page-main.full-screen {
    margin: 0;
  }

  .scan {
    padding: 16px 24px;
    text-align: center;
    background: #f7f9fc;

    .scan-title {
      padding: 16px;
      color: #3d3d3d;
      font-weight: 600;
      font-size: 24px;
      line-height: 26px;
    }
  }

  .info {
    // margin-bottom: 10px;
    padding: 10px;
    color: #828b9b;
    background: #fff;

    .mes {
      display: -webkit-box;
      height: 32px;
      overflow: hidden;
      line-height: 16px;
      text-overflow: ellipsis;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
  }

  /deep/ .green :nth-child(4) {
    background-color: #8fda94 !important;
  }

  /deep/ .red :nth-child(4) {
    background-color: #ee8d82 !important;
  }

  .no-margin {
    margin-right: 0 !important;
  }
</style>
